const Axios = require('axios')
const config = require('../utils/wxConfig.js')
const sha1 = require('js-sha1')


module.exports = ctx => {
	let time = (Date.parse( new Date())/1000)
	if (config.jsapiTicket && (time - config.jsapiTicket.time) < config.jsapiTicket.expires_in ) {
		calculate(config.jsapiTicket, ctx)
	}else{
		return	Axios.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.wechat.appID+'&secret='+config.wechat.appSecret)
		.then(function(response){
			let access = response.data
			if (access.access_token) {
				access['time'] = Date.parse( new Date())/1000
				config.accessToken = access
			}
			return Axios.get('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+response.data.access_token+'&type=jsapi')
			.then(function(res){
				let ticket = res.data
				if (ticket.ticket) {
					ticket['time'] = Date.parse( new Date())/1000
					config.jsapiTicket = ticket
					calculate(ticket, ctx)
				}
			})
			.catch(function(err){
				console.log(err);	
			});
		})
		.catch(function(err){
			console.log(err);
		});
	}
	function calculate(ticket, ctx){
		let jssdk = {
			appId:config.wechat.appID,
			nonceStr: Math.random().toString(36).substr(2),
			timestamp: Date.parse(new Date())/1000,
			url: ctx.query.url
		}
		jssdk['signature'] = sha1('jsapi_ticket='+ticket.ticket+'&noncestr='+jssdk.nonceStr+'&timestamp='+jssdk.timestamp+'&url='+jssdk.url)
		ctx.state.data = jssdk
	}
}
